﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using Microsoft.Extensions.Options;
using System.Net.Http;
using Casamiel.Common;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using System.Data;
using System.Collections.Generic;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Response.GroupPurchase;
using Newtonsoft.Json;
using System.Linq;

namespace Casamiel.Application.Commands.GroupPurchase
{
	/// <summary>
	/// 发送券
	/// </summary>
	public sealed class SendTicketCommandHandler:BaseCommandHandler,IRequestHandler<SendTicketCommand,BaseResult<string>>
	{
		/// <summary>
		/// 
		/// </summary>
		private readonly IBaseMemberConponsRepository _baseMemberConpons;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly ICasaMielSession _session;
		private readonly IMemberService _memberService;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		/// <param name="baseMemberConpons"></param>
		/// <param name="memberCouponRepository"></param>
		/// <param name="casaMielSession"></param>
		/// <param name="memberService"></param>
		public SendTicketCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings,
			IBaseMemberConponsRepository baseMemberConpons, IMemberCouponRepository memberCouponRepository, ICasaMielSession casaMielSession,
			IMemberService memberService) :
			base(netICService, httpClientFactory, settings)
		{
			_baseMemberConpons = baseMemberConpons;
			_memberCouponRepository = memberCouponRepository;
			_session = casaMielSession;
			_memberService = memberService;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<string>> Handle(SendTicketCommand request, CancellationToken cancellationToken)
		{
			var msg = "";
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}
			if (request.Flag == 1) {
				 
				var url = "v3/Activity/GetSameGrouponOrder";
				var data = new { request.OrderCode };
				
				var rsp = await PostThirdApiWithPagingAsync<List<ActivitySameGrouponOrderRsp>>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
				if (rsp.Code == 0) {
					if(rsp.Content!=null && rsp.Content.Any()) {
						foreach (var item in rsp.Content) {
							await Method(item).ConfigureAwait(false);
						}
					}
				} 
			}
			return new BaseResult<string>("", 0, msg);
		}


		private async Task<bool> Method(ActivitySameGrouponOrderRsp entity)
		{
			var member = await _memberService.FindAsync<ICasaMielSession>(entity.Mobile).ConfigureAwait(false);
			if (member == null)
			return false;
			List<BaseMemberCoupons> list = new List<BaseMemberCoupons>();
			foreach (var item in entity.OrderGoodsList) {
				var list1 = await _baseMemberConpons.GetListAsync<ICasaMielSession>(int.Parse(item.SkuCode), 1,item.Quantity).ConfigureAwait(false);
				if(list1==null || list1.Count<item.Quantity) {
					OrderLogger.Error($"{item.SkuCode},券数量不足");
					return false;
				}
				list1.ForEach(c => {
					list.Add(new BaseMemberCoupons {
						ID = c.ID,
						ProductId=c.ProductId,
						Price = c.Price, Productname = c.Productname, State = c.State,
						TicketCode = c.TicketCode
					});
				});
			}
			var membercouponlist = await _memberCouponRepository.GetListAsnyc<ICasaMielSession>(entity.OrderCode).ConfigureAwait(false);
			if (membercouponlist != null && membercouponlist.Any()) {
				await ChangeGrouponOrderStatusAsync(entity.OrderCode, entity.Mobile, 4, 0).ConfigureAwait(false);
				return false;
			}
			var s = await Ttaa(list, member.ID,entity.OrderCode).ConfigureAwait(false);
			if (s) {
				
				await ChangeGrouponOrderStatusAsync(entity.OrderCode, entity.Mobile, 4, 0).ConfigureAwait(false);
			}
			return s;
		}


		/// <summary>
		/// 改变拼团订单状态
		/// </summary>
		/// <param name="OrderCode"></param>
		/// <param name="Mobile"></param>
		/// <param name="Type">类型 1 支付完成 2 超时自动取消 3 已完成 4 已发券 5 券已使用or已转赠 6 </param>
		/// <param name="PayMethod"></param>
		/// <returns></returns>
		private async Task<BaseResult<string>> ChangeGrouponOrderStatusAsync(string OrderCode, string Mobile, int @Type, int PayMethod)
		{
			var data = new { OrderCode, Mobile, Type = @Type, PayMethod };

			var url = "v3/Activity/ChangeGrouponOrderStatus";
			var result = await PostThirdApiAsync<string>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
			return result;
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="ticketCodeList"></param>
		/// <returns></returns>
		private async Task<bool> Ttaa(List<BaseMemberCoupons> ticketCodeList,long MID,string OrderCode)
		{
			using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
				try {

				foreach (var item in ticketCodeList) {
				  bool s= await	_baseMemberConpons.UpdateAsync(item.TicketCode, 0, 1,uow).ConfigureAwait(false);
					if (!s) {
						uow.Rollback();
						return false;
					}
					var e = new MemberCoupon {
						MID = MID,
						Productid=item.ProductId,
						CreateTime = DateTime.Now,
						Ticketcode = item.TicketCode,
						Productname = item.Productname,
						State = 3,
						GiveStatus = 0,
						Price = item.Price,
						Enddate = DateTime.Now.AddYears(1),
						Startdate = DateTime.Now.AddDays(-1),
						OrderCode= OrderCode

					};
					await _memberCouponRepository.SaveAsync(e, uow).ConfigureAwait(false);
					if (e.MCID == 0) {
						uow.Rollback();
						return false;
					}

					

				}
				} catch (Exception) {
					uow.Rollback();
					 
					throw;
				}
			}
			return true;
		}
		 
	}
}
